﻿using facebook.businuss.netcore.sdk.Model;
using facebook.businuss.netcore.sdk.Sdk.IService;
using facebook.businuss.netcore.sdk.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace facebook.businuss.netcore.sdk.Sdk
{
    public class DefaultRequestExecutor : IRequestExecutor
    {
        public ResponseWrapper execute(string method, string apiUrl, Dictionary<string, object> allParams, APIContext context)
        {
            if ("GET".Equals(method)) return sendGet(apiUrl, allParams, context);
            else if ("POST".Equals(method)) return sendPost(apiUrl, allParams, context);
            else if ("DELETE".Equals(method)) return sendDelete(apiUrl, allParams, context);
            else throw new Exception("Unsupported http method. Currently only GET, POST, and DELETE are supported");
        }

        public ResponseWrapper sendDelete(string apiUrl, Dictionary<string, object> allParams, APIContext context)
        {
            throw new NotImplementedException();
        }

        public ResponseWrapper sendGet(string apiUrl, Dictionary<string, object> allParams, APIContext context)
        {
            Uri url = new Uri(RequestHelper.constructUrlString(apiUrl,allParams));


            HttpClientHandler clientHandler = new HttpClientHandler()
            {

                AutomaticDecompression = DecompressionMethods.All,
            };

            if (context.Proxy != null)
                clientHandler.Proxy = context.Proxy;
            HttpResponseMessage response = null;
            using (HttpClient client1 = new HttpClient(clientHandler))
            {
                client1.DefaultRequestHeaders.Accept.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                client1.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
                response = client1.SendAsync(request).GetAwaiter().GetResult();
            }

            return readResponse(response);
        }

        private static ResponseWrapper readResponse(HttpResponseMessage response)
        {
            try
            {
                if (response!=null&&response.StatusCode == HttpStatusCode.OK)
                {
                    return new ResponseWrapper(response.Content.ReadAsStringAsync().Result, response.Headers);
                }

                return null;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public ResponseWrapper sendPost(string apiUrl, Dictionary<string, object> allParams, APIContext context)
        {
            throw new NotImplementedException();
        }
    }
}
